// 通知公告管理

package info

import (
	"api/common"
	"api/common/logger"
	"api/common/orm"
	"api/common/web"
	"api/models"
	"net/http"
	"strings"
)

// @TagName 通知公告管理
// @Controller NoticeController
type NoticeController struct{}

// @Title 通知公告列表数据
// @Route /notice/list --> List
// @Method post
func (this *NoticeController) List(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	model := &models.Notice{}
	fields := "id, title, begin_time, end_time, sequ"
	order := "sequ desc"
	web.JsonCallBakFilter(w, inputJson, model, fields, "", order)
}

// @Title 新增通知公告信息
// @Route /notice/create --> Create
// @Method post
func (this *NoticeController) Create(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.CreateRecord(w, r, &models.Notice{})
}

// @Title 编辑通知公告信息
// @Route /notice/edit --> Edit
// @Method post
func (this *NoticeController) Edit(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.EditRecord(w, r, &models.Notice{})
}

// @Title 删除通知公告信息
// @Route /notice/delete --> Delete
// @Method post
func (this *NoticeController) Delete(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.DeleteCallBak(w, r, &models.Notice{})
}

// @Title 通知公告信息回显
// @Route /notice/echo --> Echo
// @Method post
func (this *NoticeController) Echo(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	web.EchoCallBak(w, r, &models.Notice{})
}

// @Title 发送订阅消息
// @Route /notice/send --> Send
// @Param {"userId":0, "token":"", "noticeId":0}
// @Method post
func (this *NoticeController) Send(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, msg := web.TokenCheckRequest(r)
	if msg != nil {
		web.ServeJSON(w, msg)
		return
	}

	noticeId := inputJson["noticeId"]
	if noticeId == nil || noticeId == "" {
		web.ServeJSON(w, web.JsonMsg{false, "通知id不能为空", 1})
		return
	}

	notice := &models.Notice{}
	sql := "select (case when char_length(content)>20" +
		" then concat(substr(content,1,19),'…') else content end) content," +
		" add_time from info_notice where id=?"
	conn := orm.NewOrm()
	err := conn.Raw(sql, noticeId).QueryRow(notice)
	if err != nil {
		if strings.Index(err.Error(), "no row found") == -1 {
			logger.Info("查询通知公告信息发生错误", err)
			web.ServeJSON(w, web.JsonMsg{false, "查询通知公告信息发生错误" + err.Error(), 1})
			return
		}

		web.ServeJSON(w, web.JsonMsg{false, "通知公告信息不存在", 1})
		return
	}

	// 获取作业清单(微信用户的openId)
	type Task struct {
		Name  string `json:"name"`
		Phone string `json:"phone"`
		Msg   string `json:"msg"`
	}
	dataTask := []Task{}
	sql = "select `name`, concat(phone, ' ', phone_backup) phone, weixin_id msg from student_info" +
		" where (`status`=1 or `status`=2) and weixin_id!='' order by add_time"
	_, err = conn.Raw(sql).QueryRows(&dataTask)
	if err != nil {
		logger.Error("获取作业清单发生错误", err)
		web.ServeJSON(w, web.JsonMsg{false, "获取作业清单发生错误" + err.Error(), 1})
		return
	}

	// 开始发送订阅消息
	dataFail := []Task{} // 失败列表
	sendData := []common.Item{}
	item := common.Item{
		Field: "thing3",
		Value: notice.Content,
	}
	sendData = append(sendData, item)
	item = common.Item{
		Field: "time2",
		Value: common.ToStr(notice.AddTime)[0:10],
	}
	sendData = append(sendData, item)

	for i := 0; i < len(dataTask); i += 1 {
		task := dataTask[i]
		errMsg := common.SendMsg(
			task.Msg,
			common.Config.WX.MessageTemplate.Notice,
			sendData,
		)

		if errMsg != "" {
			task.Msg = errMsg
			dataFail = append(dataFail, task)
		}
	}

	if len(dataFail) > 0 {
		result := map[string]interface{}{}
		result["success"] = false
		result["status"] = 2
		result["msg"] = "发送订阅消息发生错误"
		result["taskTotal"] = len(dataTask)
		result["dataFail"] = dataFail // 将失败列表返给后台管理员
		web.ServeJSON(w, result)
		return
	}

	web.ServeJSON(w, web.JsonMsg{true, "发送订阅消息成功", 0})
}
